#include "DInput.h"
#include "d3dUtil.h"
#include "d3dApp.h"
#include <commctrl.h>
#include <basetsd.h>

//// Changes made by zach 01/28/08
//BOOL CALLBACK EnumJoysticksCallback(const DIDEVICEINSTANCE* pdidInstance, VOID* pContext);


int Count = 0;

DInput* gDInput = 0;

DInput::DInput(DWORD keyboardCoopFlags, DWORD mouseCoopFlags, DWORD joystickCoopFlags)
{
	HRESULT hr;
	//clear the memory
	ZeroMemory(mKeyboardState, sizeof(mKeyboardState));
	ZeroMemory(&mMouseState, sizeof(mMouseState));

//	//create Direct Input Object
//	HR(DirectInput8Create(gd3dApp->getAppInstance(), DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mDInput, 0));
	hr = DirectInput8Create(NULL, DIRECTINPUT_VERSION, IID_IDirectInput8, (void**)&mDInput, 0);

	//Create Direct Input Device (keyboard), then set parameters and acquire
	hr = mDInput->CreateDevice(GUID_SysKeyboard, &mKeyboard, 0);
	hr = mKeyboard->SetDataFormat(&c_dfDIKeyboard);
//	HR(mKeyboard->SetCooperativeLevel(gd3dApp->getMainWindowHandle(), keyboardCoopFlags));
	hr = mKeyboard->SetCooperativeLevel(NULL, keyboardCoopFlags);
	hr = mKeyboard->Acquire();

	//Same as above but for mouse
	hr = mDInput->CreateDevice(GUID_SysMouse, &mMouse, 0);
	hr = mMouse->SetDataFormat(&c_dfDIMouse2);
//	hr = mMouse->SetCooperativeLevel(gd3dApp->getMainWindowHandle(), mouseCoopFlags);
hr = mMouse->SetCooperativeLevel(NULL, mouseCoopFlags);
	hr = mMouse->Acquire();

}

void DInput::poll()
{
	//poll the keyboard, find out what state keys are in
	HRESULT hr = mKeyboard->GetDeviceState(sizeof(mKeyboardState), (void**)&mKeyboardState);

	if(FAILED(hr))
	{
		//keyboard lost, zero out keyboard data structure
		ZeroMemory(mKeyboardState, sizeof(mKeyboardState));

		//try to acquire for next time we poll
		hr = mKeyboard->Acquire();
	}

}

void DInput::onLostDevice()
{
	HRESULT hr;
	ZeroMemory(&mKeyboard, sizeof(mKeyboard));

	if(mKeyboard != NULL)
		hr = mKeyboard->Acquire();

}

bool DInput::keyDown(unsigned char key)
{
	//performing a bitwise operation to see if key is down, if the bits 0x80 are set, the key is 
	//considered to be pressed
	return ((mKeyboardState[key] & 0x80) != 0);
	
}

bool DInput::mouseButtonDown(int button)
{
	return (mMouseState.rgbButtons[button] & 0x80) != 0;
}

float DInput::mouseDX()
{
	return (float)mMouseState.lX;
}

float DInput::mouseDY()
{
	return (float)mMouseState.lY;
}

float DInput::mouseDZ()
{
	return (float)mMouseState.lZ;
}
DInput::~DInput()
{
	//release Direct Input Object
	mDInput->Release();
	
	//unacquire devices, give them back to the system!!!
	mKeyboard->Unacquire();
//	mMouse->Unacquire();

	//release the devices
	mKeyboard->Release();
	mKeyboard = NULL;
//	ReleaseCOM(mMouse);

}